import json

from rest_framework import serializers
from rest_framework import validators
from XApiTestServer import models
from djcelery import models as celery_models
from XApiTestServer.utils.task_opt import CELERY_TEST_TASK


class UserSerializer(serializers.ModelSerializer):
    """
    用户信息序列化
    """
    class Meta:
        model = models.UserInfo
        fields = ['id', 'username', 'password', 'email', 'status', 'update_time']


class ProjectSerializer(serializers.ModelSerializer):
    """
    项目信息序列化
    """
    simple_desc = serializers.CharField(allow_blank=True)
    other_desc = serializers.CharField(allow_blank=True)
    class Meta:
        model = models.ProjectInfo
        fields = ['id', 'project_name', 'responsible_name', 'test_user', 'dev_user', 'publish_app', 'update_time', 'other_desc', 'simple_desc']


class ProjectSumSerializer(serializers.ModelSerializer):
    """
    项目信息概要序列化
    """
    class Meta:
        model = models.ProjectInfo
        fields = ['id', 'project_name']


class ModuleSerializer(serializers.ModelSerializer):
    """
    模块信息序列化
    """
    belong_project_name = serializers.CharField(source="belong_project.project_name", read_only=True, required=False)
    simple_desc = serializers.CharField(allow_blank=True)
    other_desc = serializers.CharField(allow_blank=True)
    class Meta:
        model = models.ModuleInfo
        fields = ['id', 'module_name', 'belong_project', 'belong_project_name', 'test_user',
                  'update_time', 'other_desc', 'simple_desc']


class ModuleSumSerializer(serializers.ModelSerializer):
    """
    模块信息概要序列化
    """
    class Meta:
        model = models.ModuleInfo
        fields = ['id', 'module_name']


class ConfigSerializer(serializers.ModelSerializer):
    """
    配置信息序列化
    """
    name = serializers.CharField(max_length=100, min_length=4,
                                 error_messages={
                                     'required': '配置名称name为必填字段',
                                     'min_length': '配置名称name，不能少于4个字符',
                                     'required': '配置名称name，不能大于100个字符',
                                 })
    # belong_project = serializers.IntegerField(
    #                              error_messages={
    #                                  'blank': '所属项目为必填字段，不能为空',
    #                                  'required': '所属项目为必填字段',
    #                              })
    belong_project_name = serializers.CharField(source="belong_project.project_name", read_only=True, required=False)

    class Meta:
        model = models.TestConfig
        fields = ['id', 'name', 'belong_project', 'belong_project_name', 'config_body', 'create_time', 'update_time',
                  'author']


class ConfigSumSerializer(serializers.ModelSerializer):
    """
    配置概要信息序列化
    """
    class Meta:
        model = models.TestConfig
        fields = ['id', 'name']


class AuthSerializer(serializers.ModelSerializer):
    """
    测试用例认证信息序列化
    """
    belong_project_name = serializers.CharField(source="belong_project.project_name", read_only=True, required=False)
    request = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    user_name = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    password = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    auth_url = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    class Meta:
        model = models.TestAuth
        fields = ["id", "name", 'belong_project', "belong_project_id", "belong_project_name", "auth_type", "user_name", "password", "auth_url", "request",
                  "author", "update_time"]


class AuthSumSerializer(serializers.ModelSerializer):
    """
    测试用例认证概要信息序列化
    """
    class Meta:
        model = models.TestAuth
        fields = ["id", "name"]


class CaseSerializer(serializers.ModelSerializer):
    """
    用例信息序列化
    """
    belong_project_name = serializers.CharField(source="belong_project.project_name", read_only=True, required=False)
    belong_module_name = serializers.CharField(source="belong_module.module_name", read_only=True, required=False)
    auth_type = serializers.CharField(source="auth.auth_type", read_only=True, required=False, allow_null=True)
    auth_name = serializers.CharField(source="auth.name", read_only=True, required=False, allow_null=True)

    class Meta:
        model = models.TestCase
        fields = ["id", "name", "belong_project", "belong_project_name", "belong_module", "belong_module_name",
                  "pre_cases", "request", "update_time", "author", "auth", "auth_type", "auth_name"]


class CaseSumSerializer(serializers.ModelSerializer):
    """
    用例概要信息序列化
    """
    class Meta:
        model = models.TestCase
        fields = ["id", "name"]


class SuiteSerializer(serializers.ModelSerializer):
    """
    测试套件序列化
    """
    belong_project_name = serializers.CharField(source="belong_project.project_name", read_only=True, required=False)
    case_num = serializers.SerializerMethodField()

    class Meta:
        model = models.TestSuite
        fields = ["id", "suite_name", "belong_project", "belong_project_name", "disabled_cnt", "update_time",  "include",
                  "case_num", "author"]

    def get_case_num(self, obj):
        return obj.include.count('[') - 1


class SuiteSumSerializer(serializers.ModelSerializer):
    """
    测试套件概要信息序列化
    """
    class Meta:
        model = models.TestSuite
        fields = ["id", "suite_name"]


class FileSerializer(serializers.ModelSerializer):
    """
    用例信息序列化
    """

    class Meta:
        model = models.FileInfo
        fields = ["id", "name", "project", "belong_project", "module", "belong_module", "file_size", "update_time",
                  "author"]


class ReportSerializer(serializers.ModelSerializer):
    """
    报告信息序列化
    """

    class Meta:
        model = models.TestReports
        fields = ["id", "report_name", "status", "testsRun", "successes", "reports", "start_at", "author"]


class PeriodicTaskSerializer(serializers.ModelSerializer):
    """
    定时任务信列表序列化
    """
    kwargs = serializers.SerializerMethodField()
    args = serializers.SerializerMethodField()
    belong_project_name = serializers.SerializerMethodField()
    test_type = serializers.SerializerMethodField()

    class Meta:
        model = celery_models.PeriodicTask
        fields = ['id', 'name', 'args', 'kwargs', 'enabled', 'date_changed', 'enabled', 'description', 'belong_project_name', 'test_type']

    def get_kwargs(self, obj):
        return json.loads(obj.kwargs)

    def get_args(self, obj):
        return json.loads(obj.args)

    def get_belong_project_name(self, obj):
        belong_project_id = int(obj.description)
        project_name = models.ProjectInfo.objects.get(id=belong_project_id).project_name
        return project_name

    def get_test_type(self, obj):
        test_task = obj.task
        for key, value in CELERY_TEST_TASK.items():
            if test_task == value:
                return key
        return ''


class MockSerializer(serializers.ModelSerializer):
    """
    报告信息序列化
    """
    request = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    class Meta:
        model = models.MockInfo
        fields = ["id", "name", "mock_url", "request_method", "request", "response_body", "author", "update_time"]
